<?php
abstract class Paysdk
{
    private static $_instance = array();

    public static function instance($type)
    {
        if (!isset(self::$_instance[$type]))
        {
            $class = 'paysdk_'.$type;
            if (!class_exists($class))
            {
                throw new Exception(sprintf('The payment could not be loaded: %s', $type));
            }
            $config = Kohana::config('paysdk.'.$type);
            self::$_instance[$type] = new $class($config);
        }
        return self::$_instance[$type];
    }


    protected $pay_config = array();
    protected $paytype;
    protected $param = array();

    public function __construct($config = array())
    {
        $this->pay_config = $config;
    }

    public function get_gateway_url()
    {
        return $this->gateway_url;
    }

    public function get_form($button_name="")
    {
        $str = '<form method="POST" action="'.$this->get_gateway_url().'">';
        foreach ($this->param as $k => $v)
        {
            $str .= '<input type="hidden" name="'.$k.'" value="'.$v.'" />'."\n";
        }
        if(!empty($button_name)){
        $str .= '<input type="submit" value="'.$button_name.'" id="submit-order"></form>';}
        else
        {$str.='</form>';}
        return $str;
    }

    public function get_param($key = '')
    {
        if ($key)
        {
            return isset($this->param[$key]) ? $this->param[$key] : '';
        }
        return $this->param;
    }

    public function set_param($key, $value = '')
    {
        if (is_array($key))
        {
            $this->param = array_merge($this->param, $key);
        }
        else
        {
            $this->param[$key] = $value;
        }
    }

    //获取客户端IP
    protected function get_client_ip()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
        else $ip = "unknown";
        if(!preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) return '0.0.0.0';
        return($ip);
    }
}
